#download pics with 3 threads

import threading
import urllib
import jsTool


class Downloader(threading.Thread):

    def __init__(self, threadname, collectSet,path,kind):
        threading.Thread.__init__(self, name = threadname)
        self.kSet = collectSet
        self.path=path
        self.kind=kind
        

    
    def run(self):
        for link in self.kSet.keys():
            fname = self.path+'/'+self.kind+link.split('/')[-2]+'['+self.kSet[link]['title']+'].jpg'
            #fname = 'smallpics/'+k+'/'+link.split('/')[-1]+'cxc'+kSet[link]['title']+'cxc'+kSet[link]['pic'].replace('/','-')
            url  = self.kSet[link]['pic']
            self.imgDownload(url,fname)

            print self.kSet[link]['pic'],
            print fname
            #print fname2link
            
    def imgDownload (self,url , fname):
        try:
            f= file(fname,'wb')
            f.write(urllib.urlopen(url).read())
            f.close()
            return True
        except Exception , e:
            print e
            print 'Download img fail'
            return False


def main(path):
    cSet = jsTool.j2o('collectSet.json')
    kind = ['music','book','movie']
    print 'Starting threads ...'
    for k in kind :
        kSet = cSet[k]
        download = Downloader(k+' Downloader',kSet,path,k)
        download.start()
        download.join()
    print 'All threads have terminated.'
    
if __name__ == '__main__':
    main('home')
